<template>
  <div>
      <!-- <button @click="connect">连接</button>
      <button @click="sendMessage" :disabled="!connected">发送消息</button>
      <button @click="disconnect" :disabled="!connected">断开</button> -->
  </div>
</template>

<script setup>
import { ref,onMounted,onUnmounted } from 'vue';
import bus from '../tools/eventBus'
const ws = ref(null);
const connected = ref(false);

onMounted(() => {
  connect();
});
onUnmounted(() => {
  disconnect();
})
const connect = () => {
  ws.value = new WebSocket('ws://10.204.253.11:8900/hello');
  // 实时监听连接
  ws.value.onopen = (ever) => {
    console.log('onopen');
      connected.value = true;
  };
  // 实时监听关闭
  ws.value.onclose = () => {
      connected.value = false;
      console.log('onopen');
  };
  // 实时监听数据
  ws.value.onmessage = (event) => {
    // 处理收到的消息数据
     if (event && event.data) {
      // console.log('收到消息:', event.data);
      bus.emit('realTime',JSON.parse(event.data))
    } else {
      console.error('onmessage 事件处理器的 event 参数无效');
    }
  }

  // 实时监听错误
  ws.value.onerror = (error) => {
      console.error('Error:', error);
  };

};

const sendMessage = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send('李延超');
  }
};

const disconnect = () => {
  if (ws.value) {
      ws.value.close();
      ws.value = null;
  }
};
</script>